package com.hongji.lms5xxcommunicator.grid.config;

import com.hongji.lms5xxcommunicator.grid.RasterGrid;
import com.hongji.lms5xxcommunicator.grid.core.GridSpec;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;

@Slf4j
@Service
@RequiredArgsConstructor
public class RasterGridHolder {

    private final GridProps props;

    @Getter
    private RasterGrid grid;

    // 新增：把初始化时的规格保存下来，供首帧构建使用
    @Getter
    private GridSpec spec;

    /** 扩容留白（单位同 x/y） */
    @Getter
    private double pad = 0.0;

    @PostConstruct
    public void init() {
        if (props.getSpec() == null) {
            throw new IllegalStateException("grid.spec 未配置：请在 yml 中提供 x0/x1/y0/y1/dx/dy");
        }
        spec = new GridSpec(
                props.getSpec().getX0(), props.getSpec().getX1(),
                props.getSpec().getY0(), props.getSpec().getY1(),
                props.getSpec().getDx(), props.getSpec().getDy()
        );

        grid = new RasterGrid(spec).setUpdateMode(props.getUpdateMode());

        if (props.getVolume() != null) {
            grid.configureVolume(
                    props.getVolume().getBaseline(),
                    Boolean.TRUE.equals(props.getVolume().getClampNegative())
            );
        }

        if (props.getPad() != null) {
            pad = Math.max(0.0, props.getPad());
        }

        if (log.isInfoEnabled()) {
            log.info("[RasterGridHolder] 初始化完成: spec=({},{}; {},{}) dx={}, dy={}, mode={}, pad={}, volume={}/{}",
                    spec.x0, spec.x1, spec.y0, spec.y1, spec.dx, spec.dy,
                    props.getUpdateMode(),
                    pad,
                    props.getVolume() == null ? "null" : props.getVolume().getBaseline(),
                    props.getVolume() == null ? "null" : props.getVolume().getClampNegative());
        }
    }

    /** 拿到全局唯一的 RasterGrid 实例 */
    public RasterGrid get() { return grid; }
}
